<template>
  <div class="homepage-container">
    <div v-if="homeType==='2'">
      <div class="top">
        <div class="icon">
          <img src="../../assets/user-icon.png"
               alt=""/>
        </div>
        <div class="detail">
          <h2>您好，欢迎使用！</h2>
          <div class="content">
            <div class="user-info">
              <!-- <img src="../../assets/welcome-ic.png"
                 alt=""> -->
              <div class="text">
                <!-- <p>您好，欢迎使用中建协兴国际咨询管理系统！</p> -->
                <span>{{ userInfo.user_name }}-{{
                    userInfo.job_list[0] &&  userInfo.job_list[0].job_name
                  }}</span>
              </div>
            </div>
          </div>
        </div>
        <div class="statics">
          <div class="statics-num">
            <p>项目数</p>
            <span>{{ totalCount }}</span>
          </div>
        </div>
      </div>
      <p class="deskTop"
         @click="openDeskSet">桌面设置</p>
      <div class="gridBox"
           style="display:flex;">
        <div class="left"
             style="flex:2;">
          <grid-layout :layout.sync="leftLayout"
                       :col-num="12"
                       :row-height="30"
                       :is-draggable="false"
                       :is-resizable="false"
                       :is-mirrored="false"
                       :vertical-compact="true"
                       @layout-updated="layoutLeftUpdatedEvent"
                       :margin="[20,20]"
                       :use-css-transforms="true">
            <grid-item v-for="item in leftLayout"
                       :x="item.x"
                       :y="item.y"
                       :w="item.w"
                       :h="item.h"
                       :minW="item.minW"
                       :minH="item.minH"
                       :i="item.i"
                       :key="item.i">
              <component :key="item.i"
                         :is="item.router"
                         :height="item.h"
                         :type="item.i"
                         :projectId="choosedProject"></component>
            </grid-item>
          </grid-layout>
        </div>
        <div class="right"
             style="flex:1;margin-left: -20px">
          <grid-layout :layout.sync="rightLayout"
                       :col-num="12"
                       :row-height="30"
                       :is-draggable="false"
                       :is-resizable="false"
                       :is-mirrored="false"
                       :vertical-compact="true"
                       :margin="[20,20]"
                       @layout-updated="layoutRightUpdatedEvent"
                       :use-css-transforms="true">
            <grid-item v-for="item in rightLayout"
                       :x="item.x"
                       :y="item.y"
                       :w="item.w"
                       :h="item.h"
                       :minW="item.minW"
                       :minH="item.minH"
                       :i="item.i"
                       :key="item.i">
              <component :key="item.i"
                         :is="item.router"
                         :height="item.h"
                         :type="item.i"
                         :projectId="choosedProject"></component>
            </grid-item>
          </grid-layout>
        </div>
      </div>
    </div>
    <iframe :src="homeUrl"
            style="width:100%;height:100%;"
            v-if="homeType==='1'"
            frameborder="0"></iframe>
    <!-- <iframe src="http://console.hibuilding.cn/"
            width="100%"
            height="100%"
            frameborder="0"></iframe> -->
    <el-dialog title="桌面设置"
               :visible.sync="setVisible">
      <el-checkbox-group v-model="checkList"
                         @change="selSet">
        <el-checkbox label="1">项目地图/项目管理</el-checkbox>
        <el-checkbox label="2">快捷导航</el-checkbox>
        <el-checkbox label="3">动态</el-checkbox>
        <el-checkbox label="4">人机料概况</el-checkbox>
      </el-checkbox-group>
      <div slot="footer"
           class="dialog-footer">
        <el-button @click="closeSet">取 消</el-button>
        <el-button type="primary"
                   @click="saveSet('save')">确 定
        </el-button>
      </div>
    </el-dialog>
    <el-dialog
      width="80%"
      title="监控台"
      :visible.sync="monitoringStationVisible">
      <div class="screen-content">
        <screen-list isDemo></screen-list>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import VueGridLayout from 'vue-grid-layout';
import PeopleManage from "./components/PeopleManage";
import ProjectManage from "./components/ProjectManage";
import MenuList from "./components/MenuList";
import MessageList from "./components/MessageList";
import {ProjectListApi} from "@/services/ProjectCenter";
import {standardCodeApi} from "@/services/StandardCode";
import {SendCodeApi} from '@/services/Public'
// /pages/ProjectCenter/ScreenList
import ScreenList from "@/pages/ProjectCenter/ScreenList";

export default {
  name: "Home",
  data() {
    return {
      monitoringStationVisible: false,
      leftLayout: [
        // { "x": 0, "y": 0, "w": 12, "h": 8, "minW": 12, "minH": 8, "i": "1", sort: '', router: 'ProjectManage' },//项目管理
        // { "x": 0, "y": 1, "w": 12, "h": 15, "minW": 12, "minH": 15, "i": "4", sort: '', router: 'PeopleManage' }, //人机概况
      ],
      rightLayout: [
        // { "x": 0, "y": 0, "w": 12, "h": 6, "minW": 12, "minH": 6, "i": "2", sort: '', router: 'MenuList' }, //导航
        // { "x": 12, "y": 9, "w": 12, "h": 17, "minW": 12, "minH": 17, "i": "3", sort: '', router: 'MessageList' }, //动态
      ],
      checkList: [],
      saveCheckedlist: ['1', '2', '3', '4'], //默认值
      setVisible: false,
      requestParam: {
        search: "",
        created_start: "",
        created_end: "",
        province_no: "",
        city_no: "",
        area_no: "",
        major_type: "",
        status: "",
        is_page: 1,
        page: 1,
        per_page: 4,
        dateRange: "",
        module_id: '2',
        conditions: [],
      },
      activeTab: "userMange",
      // // 项目数据
      projectList: {
        list: [],
        total_count: 0
      },
      totalCount: 0,
      // 当前选择的项目
      choosedProject: "",
      requestManageParam: {
        conditions: [],
        company_id: '',
        module_id: '1',
        province_no: '',
        city_no: '',
        area_no: '',
        is_page: 1,
        page: 1,
        page_size: 4,
      },
      //新接口使用的项目列表
      showTopProjectList: {
        list: [],
        total_count: 0
      },
      // 咨询项数据
      issueStatics: {
        count: 0,
        indexs: {}
      },
      // 用户信息
      userInfo: {
        user_name: "",
        job_list: [{job_name: ""}]
      },
      // 建筑类型标准码
      buildingTypeCode: [],
      // 建筑类型标准码map
      buildingTypeMap: new Map(),
      projectEchart: {},
      leftCompList: {
        '1': {"x": 0, "y": 0, "w": 12, "h": 8, "minW": 12, "minH": 8, "i": "1", router: 'ProjectManage'},
        '4': {"x": 0, "y": 0, "w": 12, "h": 15, "minW": 12, "minH": 15, "i": "4", router: 'PeopleManage'}
      },
      rightCompList: {
        '2': {"x": 8, "y": 0, "w": 12, "h": 6, "minW": 12, "minH": 6, "i": "2", router: 'MenuList'},
        '3': {"x": 8, "y": 0, "w": 12, "h": 17, "minW": 12, "minH": 17, "i": "3", router: 'MessageList'}
      },
      // 判断首页类型，1为外部页面，2为系统内置页面
      homeType: '2',
      homeUrl: '',
      user: {}
    };
  },
  components: {
    GridLayout: VueGridLayout.GridLayout,
    GridItem: VueGridLayout.GridItem,
    PeopleManage,
    ProjectManage,
    MenuList,
    MessageList,
    ScreenList
  },
  methods: {
    layoutLeftUpdatedEvent(newLefttLayout) {
      this.saveSet('uplate')
    },
    layoutRightUpdatedEvent(newRightLayout) {
      this.saveSet('uplate')
    },
    //删除后对齐
    removeItem(val) {
      const index = this.layout.map(item => item.i).indexOf(val);
      this.layout.splice(index, 1);
      this.saveCheckedlist.splice(index, 1);
    },
    //桌面设置弹窗
    openDeskSet() {
      this.setVisible = true
      // this.getUser()
    },
    //添加组件
    selSet(val) {
      this.leftLayout = []
      this.rightLayout = []
      this.checkList.map((item) => {
        if (item === '1' || item === '4') {
          let obj = this.leftCompList[item]
          let len = this.leftLayout.length
          obj.y = len
          this.leftLayout.push(obj)
        }
        if (item === '2' || item === '3') {
          let obj = this.rightCompList[item]
          let len = this.rightLayout.length
          obj.y = len
          this.rightLayout.push(obj)
        }
      })
    },
    //获取用户保存的组件
    getUser() {
      this.leftLayout = []
      this.rightLayout = []
      ProjectListApi.getUserComponent({}).then(res => {
        if (res.code === 0) {
          if (res.data.id === '') {
            //用户未选中时默认全部选中
            this.checkList = this.saveCheckedlist
          } else if (res.data.id == '-1') {
            //用户全部不选
            this.checkList = []
          } else {
            let defaultArr = []
            let backObj = JSON.parse(res.data.id)
            //索引值是否存在
            for (var i in backObj) {
              defaultArr.push(backObj[i])
              this.getSort(defaultArr)
              if (backObj[i].i == '1' || backObj[i].i == '4') {
                this.$set(this.leftCompList, backObj[i].i, backObj[i])
              } else {
                this.$set(this.rightCompList, backObj[i].i, backObj[i])
              }
            }
          }
          this.selSet(this.checkList)
        }
      });
    },
    //根据返回的索引值排序
    getSort(defaultArr) {
      const sortAndMap = (defaultArr = []) => {
        const copy = defaultArr.slice();
        const sorter = (a, b) => {
          return a['sort'] - b['sort'];
        };
        copy.sort(sorter);
        const res = copy.map(({i, index}) => {
          return i;
        });
        return res;
      };
      this.checkList = sortAndMap(defaultArr)
    },
    //桌面设置保存
    saveSet(type) {
      var obj = {}
      var all = {...this.leftCompList, ...this.rightCompList}
      for (var key in all) {
        this.checkList.forEach((ele, i) => {
          if (ele === all[key].i) {
            //用索引值判断组件顺序
            this.$set(all[key], 'sort', i)
            this.$set(obj, key, all[key])
          }
        })
      }
      let checked = ''
      if (this.checkList.length === 0) {
        //用户全部不选时传-1
        checked = '-1'
      } else {
        checked = JSON.stringify(obj)
      }
      ProjectListApi.saveUserComponent({
        data: {
          id: checked
        }
      }).then(res => {
        if (res.code === 0) {
          if (type === 'save') {
            this.$message.success('设置成功!')
            this.setVisible = false
          }
        }
      });
    },
    //取消
    closeSet() {
      this.setVisible = false
      this.checkList = []
    },
    //获取项目数据(改)
    // getProjectManageList () {
    //   this.requestManageParam.company_id = this.userInfo.comp_id
    //   ProjectListApi.getProjectManageList({
    //     data: this.requestManageParam
    //   }).then(res => {
    //     if (res.code === 0) {
    //       this.showTopProjectList = res.data
    //     }
    //   });
    // },
    // 获取项目数据
    async getProjectList() {
      const res = await ProjectListApi.getProjectManageList({
        data: this.requestParam
      })
      if (res.code === 0) {
        this.choosedProject = "";
        let list = [];
        res.data.list.map(item => {
          let buildingType = this.buildingTypeMap.get(item.building_type) || {};
          item.buildingTypeName = buildingType.name;
        });
        this.totalCount = res.data.total_count || 0
        this.projectList = JSON.parse(JSON.stringify(res.data));
        this.projectList.list.map(item => {
          list.push(item.project_id);
        });
        this.choosedProject = list.join(",");

        this.projectList.list.unshift({
          project_id: this.choosedProject,
          project_name: "全部"
        });
        // this.projectList.list.map((item) => {
        //   let buildingType = this.buildingTypeMap.get(item.building_type)
        //   item.buildingTypeName = buildingType.name
        // })
      }
    },

    // 获取建筑类型标准码
    getBuildingTypeCode() {
      return standardCodeApi
        .getStandardCodeData({
          data: {
            code_type: "buildingType"
          }
        })
        .then(res => {
          if (res.code === 0) {
            this.buildingTypeCode = res.data.list;
            window.localStorage.setItem(
              "buildingTypeCode",
              JSON.stringify(res.data.list)
            );
            this.buildingTypeCode.map(item => {
              this.buildingTypeMap.set(item.value, item);
            });
          }
        });
    },
    // 根据域名获取首页地址
    getHomepageUrl() {
      return SendCodeApi.getHomepageUrl({
        params: {
          host: window.location.host
          // host: 'localhost'
        }
      }).then(res => {
        if (res.code === 0 && res.data) {
          this.homeUrl = this.handleUrl(res.data.link)
          this.homeType = res.data.type
        }
      })
    },
    // 处理url，将所需参数注入
    handleUrl(link = '') {
      let list = link.split('?')
      // 解析url，获得目标网址
      // 根据长度判断，list长度为3的是低代码平台链接，为2的是普通网址链接
      let host = ''
      if (list.length === 3) {
        host = list[0] + '?' + list[1]
      } else {
        host = list[0]
      }
      // 获取携带的参数
      let params = list[2] ? list[2].split('&') : list[1].split('&')
      // 处理后的数组
      let res = []

      params.map((item) => {
        // 遍历参数列表，解析出key和要携带的值
        let key = item.split('=')[0]
        let value = item.split('=')[1]
        // 判断是否是动态注入参数还是普通参数
        let reg = /^\$\{.*\}$/
        let str = ''
        if (reg.test(value)) {
          // 因为分割出的值是类似{user.short_key}格式的，需要把前后的大括号去掉
          let valueLen = value.length
          // 最后得到user.short_key这样的格式，表示全局有一个user对象，取其中short_key的值
          value = value.substr(2, valueLen - 3)
          let targetObj = value.split('.')[0]
          let targetObjKey = value.split('.')[1]

          if (this[targetObj]) {
            str = key + '=' + this[targetObj][targetObjKey]
          } else {
            str = key + '=' + ''
          }
        } else {
          str = key + '=' + value
        }
        res.push(str)
      })
      let newLink = host + '?' + res.join('&')
      return newLink
    },
    // 数字块获取当前项目是否是示范项目
    async getIsDemoProject() {
      // 从localStorage choosedProject获取project_id
      let choosedProjectStr = window.localStorage.getItem('choosedProject') || '{}'
      const {data} = await standardCodeApi.getScreenBlockDataAPI({
        data: {
          unit_no: 'hbd_demonstrate_project',
          project_id: JSON.parse(choosedProjectStr).project_id
        }
      })
      return data.list[0].col_values[0]
    },
  },
  async created() {
  },
  async mounted() {
    console.log(1111)
    let userInfo = window.localStorage.getItem('userInfo') || '{}'
    this.user = JSON.parse(userInfo)
    await this.getHomepageUrl()
    if (this.homeType === '2') {
      this.getUser()

      let userInfoLocal = window.localStorage.getItem("userInfo") || "{}";
      this.userInfo = JSON.parse(userInfoLocal);
      // let token = window.sessionStorage.getItem("access_token");
      let token = window.localStorage.getItem("access_token");
      let buildingTypeCodeLocal = window.localStorage.getItem("buildingTypeCode");
      if (buildingTypeCodeLocal) {
        this.buildingTypeCode = JSON.parse(buildingTypeCodeLocal);
        this.buildingTypeCode.map(item => {
          this.buildingTypeMap.set(item.value, item);
        });
      } else {
        await this.getBuildingTypeCode();
      }
      // this.getProjectManageList()
     await this.getProjectList();
      // this.getIssueStatics()
    }
    // 根据域名判断是否显示monitoringStationVisible
    let urlList = ['zjjzyxh.hibuilding.cn']
    let host = window.location.host
    if (!urlList.includes(host)) {
      let isDemoProject = await this.getIsDemoProject()
      if (+isDemoProject) {
        this.monitoringStationVisible = true
      }
    }
  }
};
</script>
<style scoped lang="scss">
.homepage-container {
  width: 100%;
  height: 100%;
  background-color: #eee;

  /deep/ .el-input .el-input__inner {
    background: none !important;
    border: none !important;
    color: #1890ff;
  }

  .top {
    width: 100%;
    height: 140px;
    background-image: url("../../assets/home-bg.png");
    background-repeat: no-repeat;
    background-size: 100% 100%;
    background-color: #fff;
    // margin-bottom: 24px;
    padding: 32px;
    display: flex;
    justify-content: flex-start;
    align-items: center;

    .icon {
      width: 48px;
      height: 48px;
      margin-right: 12px;

      img {
        width: 48px;
        height: 48px;
      }
    }

    .detail {
      flex: 1;

      h2 {
        font-size: 16px;
        color: #fff;
        font-weight: normal;
        margin-bottom: 8px;
      }

      .content {
        display: flex;
        justify-content: space-between;
        align-items: center;

        .user-info {
          display: flex;
          justify-content: flex-start;

          img {
            width: 48px;
            height: 48px;
            margin-right: 12px;
          }

          .text {
            p {
              font-size: 16px;
              color: #fff;
              font-weight: bold;
              margin-bottom: 10px;
            }

            span {
              font-size: 12px;
              color: rgba($color: #fff, $alpha: 0.85);
            }
          }
        }
      }
    }

    .statics {
      width: 260px;
      height: 100px;
      display: flex;
      justify-content: flex-end;
      align-items: center;

      .line {
        width: 1px;
        height: 40px;
        background-color: #e9e9e9;
        margin: 0 0 0 50px;
      }

      .statics-num {
        text-align: right;

        flex: 1;

        p {
          font-size: 14px;
          color: #fff;
          margin-bottom: 5px;
        }

        span {
          font-size: 24px;
          font-weight: bold;
          color: #fff;
          line-height: 38px;
          height: 38px;
        }
      }
    }
  }

  .deskTop {
    cursor: pointer;
    display: block;
    padding: 5px 10px;
    font-size: 15px;
    background: #fff;
    margin-bottom: 15px;
  }

  .remove {
    cursor: pointer;
    position: absolute;
    top: 5px;
    right: 10px;
  }

  .gridBox {
    margin: -20px;
  }
}
// 弹窗显示竖滚动条
.screen-content {
  overflow-y: auto;
  max-height: 600px;
}
</style>
